package com.myutil.qiniu;

import java.util.Arrays;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myutil.utils.ConfigFileUtils;
import com.qiniu.cdn.CdnManager;
import com.qiniu.cdn.CdnResult.RefreshResult;
import com.qiniu.util.Auth;

public class RefreshCndUrl {
	
	private static RefreshResult refreshCdnFiles(String qiniu_accessKey, String qiniu_secretKey,String domain,String bucket, String[] keys) {
		//密钥配置
        Auth auth = Auth.create(qiniu_accessKey, qiniu_secretKey);
        //实例化一个BucketManager对象
        CdnManager cdnManager = new CdnManager(auth);
        
        //String domain="private-easyis.xiaoyung.com";
        String[] urls=new String[keys.length];
        for (int i = 0; i < urls.length; i++) {
			urls[i]="https://"+domain+"/"+keys[i];// 只刷新https,https和http 访问都生效,只刷新http http访问生效 https访问还有缓存
		}
        try {
        	System.out.println("refreshUrls:"+Arrays.toString(urls));
			return cdnManager.refreshUrls(urls);
        } catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String getQiNiuDownloadUrl(String qiniu_accessKey, String qiniu_secretKey, boolean isPrivateBucket,
			String domain, String key, Long expires) {
		if (expires == null) {
			expires = 3600l;
		}
		if(!domain.startsWith("http://") &&!domain.startsWith("https://") ) {
			domain = "https://" + domain;
		}
		if (!isPrivateBucket) {
			return domain + "/" + key;
		}
		// 密钥配置
		Auth auth = Auth.create(qiniu_accessKey, qiniu_secretKey);
		// 构造私有空间的需要生成的下载的链接
		String URL = domain + "/" + key;// http://bucketdomain/key
		String downloadRUL = auth.privateDownloadUrl(URL, expires);
		return downloadRUL;
	}
	public static void main(String[] args) {
		JSONObject config = ConfigFileUtils.readFileToJson(args[1]);//-f D:\test\ssl\qiniu.conf
		
		String accessKey = config.getString("accessKey");
		String secretKey = config.getString("secretKey");
		
		String bucket ="private-easyis";
		String[] keys= new String[] {"wx.jpg"};

		String domain="private-easyis.xiaoyung.com";

		RefreshResult result = refreshCdnFiles(accessKey,secretKey,domain,bucket,keys);
		System.out.println(JSON.toJSONString(result));
		
		/*String key="wx.jpg";
		String url = getQiNiuDownloadUrl(accessKey,  secretKey, true,domain, key,null);
		
		System.out.println(url);*/
		
	}
}
